from django.shortcuts import render,redirect
from app01 import models
from app01.utils.pagination import  Pagination
from app01.utils.form import AdminModelForm
from app01.utils.md5file import md5

def admin_list(request):
    data_dict = {}
    # 前端传过来的参数
    search_data = request.GET.get('q', '')
    if search_data:
        # 把前端传过来的参数放到字典里
        data_dict['name__contains'] = search_data
    queryset = models.Admin.objects.filter(**data_dict)
    page_object = Pagination(request, queryset)
    context={
        'queryset':queryset,
        "page_string":page_object.html(),
        "search_data":search_data

    }
    return render(request,'admin_list.html',context)

def admin_add(request):
    if request.method == "GET":
        form =AdminModelForm()
        return render(request,'addchage.html',{'form':form,'title':"新建管理员"})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return  redirect('/admin/list/')
    else:
        return render(request,'addchage.html',{'form':form,'title':"新建管理员"})

def admin_delete(request,nid):
    models.Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list/')

def admin_edit(request,nid):
    row_objet=models.Admin.objects.filter(id=nid).first()
    if request.method=='GET':
        form = AdminModelForm(instance=row_objet)
        title="编辑管理员"
        return  render(request,'editchage.html',{'form':form,'title':title})
    form = AdminModelForm(data=request.POST,instance=row_objet)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request,'editchage.html',{'form':form,'title':"编辑管理员"})

def admin_reset(request,nid):
   models.Admin.objects.filter(id=nid).update(password=md5('123456'))
   return redirect('/admin/list/')